#include "gamewindow.h"
#include <QKeyEvent>
#include <QRandomGenerator>
#include <QGraphicsPixmapItem>
#include <QDebug>

// ================= 玩家类实现 =================
Player::Player(QGraphicsItem *parent) : QGraphicsPixmapItem(parent) {
    // 加载玩家图片（确保资源路径正确）
    setPixmap(QPixmap(":/images/player.png").scaled(50, 50, Qt::KeepAspectRatio, Qt::SmoothTransformation));
    isJumping = false;
    velocity = 0;
    jumpCount = 0;
    maxJumpCount = 2; // 二连跳
}

void Player::jump() {
    if (jumpCount < maxJumpCount) {
        velocity = -15;
        isJumping = true;
        jumpCount++;
    }
}

void Player::updatePosition() {
    if (isJumping) {
        setPos(x(), y() + velocity);
        velocity += 0.5; // 重力
        if (y() >= 250) { // 地面高度（根据背景图调整）
            setPos(x(), 250);
            isJumping = false;
            velocity = 0;
            jumpCount = 0;
        }
    }
}

// ================= 游戏窗口类实现 =================
GameWindow::GameWindow(QWidget *parent) : QMainWindow(parent) {
    // 初始化场景和视图
    scene = new QGraphicsScene(this);
    view = new QGraphicsView(scene);
    setCentralWidget(view);

    // 窗口属性
    setFixedSize(800, 400);
    view->setFixedSize(800, 400);
    view->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
    view->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);

    // 加载背景图片（关键！）
    QGraphicsPixmapItem *bg = new QGraphicsPixmapItem(QPixmap(":/background.jpg").scaled(800, 400));
    scene->addItem(bg);
    bg->setZValue(-1); // 确保背景在最底层

    // 初始化玩家
    player = new Player();
    player->setPos(100, 250); // 初始位置（根据背景图地面调整）
    scene->addItem(player);

    // 初始化计时器
    timer = new QTimer(this);
    connect(timer, &QTimer::timeout, this, &GameWindow::updateGame);
    timer->start(30); // 约33FPS

    resetGame();
}

void GameWindow::keyPressEvent(QKeyEvent *event) {
    if (isGameOver && event->key() == Qt::Key_R) {
        resetGame(); // 按R键重启
    } else if (!isGameOver) {
        if (event->key() == Qt::Key_Space || event->key() == Qt::Key_Up) {
            player->jump();
        }
    }
}

void GameWindow::updateGame() {
    if (!isGameOver) {
        player->updatePosition();
        spawnObstacle();
        checkCollision();
        score++;
        setWindowTitle(QString("跑酷游戏 | 得分: %1 | 剩余跳跃: %2")
                           .arg(score).arg(player->maxJumpCount - player->jumpCount));
    }
}

void GameWindow::spawnObstacle() {
    // 障碍物生成逻辑（5%概率）
    if (QRandomGenerator::global()->bounded(100) < 5) {
        QGraphicsPixmapItem *obstacle = new QGraphicsPixmapItem(QPixmap(":/images/obstacle.png").scaled(40, 40));
        obstacle->setPos(800, 260); // 地面上的位置
        scene->addItem(obstacle);
    }

    // 移动所有障碍物
    for (auto item : scene->items()) {
        if (item != player && dynamic_cast<QGraphicsPixmapItem*>(item)) {
            item->setPos(item->x() - 7, item->y());
            if (item->x() < -50) {
                scene->removeItem(item);
                delete item;
            }
        }
    }
}

void GameWindow::checkCollision() {
    // 精确碰撞检测（基于图片形状）
    for (auto item : scene->collidingItems(player)) {
        if (dynamic_cast<QGraphicsPixmapItem*>(item)) {
            gameOver();
            return;
        }
    }
}

void GameWindow::gameOver() {
    isGameOver = true;
    timer->stop();
    QGraphicsTextItem *text = scene->addText("游戏结束！按R重新开始", QFont("Arial", 24));
    text->setDefaultTextColor(Qt::white);
    text->setPos(250, 150);
}

void GameWindow::resetGame() {
    // 清理所有障碍物
    for (auto item : scene->items()) {
        if (item != player && dynamic_cast<QGraphicsPixmapItem*>(item)) {
            scene->removeItem(item);
            delete item;
        }
    }
    // 重置玩家状态
    player->setPos(100, 250);
    player->isJumping = false;
    player->jumpCount = 0;
    score = 0;
    isGameOver = false;
    if (!timer->isActive()) timer->start();
}